# -*- coding: utf-8 -*-

import requests
import json
import hashlib
import time
import _thread
from urllib.parse import urlencode

"""
多个用户开播
Created on Tue Jul 27 12:41:39 2021

@author: Administrator
"""

def getHtml(url, paramss, type = "post", userMap= {}):
    try:
        header = {'Content-Type': 'application/json; charset=UTF-8',
            "app_type": "1",
            "version": "1.21.38-test210617-1" }
        if("null" != userMap.get("token","null")):
            header["Authorization"] = userMap["token"]


        # params:{uid=40076, oid=43296, key=43296, type=0, gid=43, gift_type=1, num=1, plat=android, yzt=56070fae6b37ad772ae6ed994a082038}
        # 代理
        # prox = {}
        
        if("post" == type):
            if ("null" != userMap.get("yzt", "null")):
                url += userMap["yzt"]
            print("================  请求地址和参数  ======================")
            print(url)
            print(paramss)
            print("========================================================")
            data = requests.post(url, data=paramss, headers=header, timeout=2)
        else:
            data = requests.get(url, data=paramss, headers=header, timeout=2)
        data.encoding = "utf-8"
        # print(data.text)
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# 有的接口需要yzt参数
def getYzt(mydata):
    mydata = mydata + "a4be9f32637e217fb8dbbcae75759fb3"
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()

# Url参数添加验证码
def getUrlYzt(account, password):
    cdt = str(round(time.time() * 1000))
    mydata = account + password + cdt
    yzt = hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    s_act = account + "_" + password + "_" + yzt
    return "?act="+s_act+"&cdt="+cdt

"""
==============================================================================
    实际用户API接口调用
==============================================================================
"""
# 登录将登录数据放在文件中
def login(phone, code="831246"): # 831246 202088
    # phone = "18782927715"
    # paramss =  '{"uid":"40026", "amount":"9800"}'
    paramss = {"code": code, "cell":phone, "did":"imei866182040064619",
               "mac":"3C:86:D1:5A:EB:13", "dev":"", "plat":"vivo_V1928A", "ver":"28_9", 
               "sys":"androidphone", "sver":"1.21.39-test210726_18", "firm":"9", 
               "mart":"android", "token":"", "ip":"192.168.0.201", "source":"and-0", 
               "yzt":getYzt(phone), "lat":"30.554378", 
               "lng":"104.07132", "city":"510100", "cityname":"成都市", 
               "state":"510000", "statename":"四川省"}
    
    dd = str(paramss)
    # print(dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = getHtml(URLHOST+"yonghu/celllogin", par)
    print(data)

    userMaps = {}
    try:
        json_to_python = json.loads(data)
        token = json_to_python['Data']["token"]
        uid = json_to_python['Data']["uid"]
        cell = json_to_python['Data']["cell"]
        pwd = json_to_python['Data']["password"]
        yzt = getUrlYzt(cell, pwd)

        userMaps = {"token": token, "uid": uid, "yzt": yzt}
    except Exception as e1:
        print("===json 解析出错:" + str(e1))
    return userMaps


# 验证码
def getCode(cell):
    paramss = {"cell": cell, "yzt": getYzt(cell)}
    text = URLHOST + "yonghu/getloginsms"+"?cell="+cell +"&yzt="+getYzt(cell)
    response = getHtml(text, "", "get")
    print(response)

# 实名认证  room_type == 4 语音
def 开始直播(userMap, location):
    # {lat=30.554227, lng=104.071163, state=510000, statename=四川省, city=510100, cityname=成都市, uid=40076, labelid=1, room_type=1}
    paramss = {"uid": userMap["uid"], "lat": "30.554227", "lng": "104.071163",
               "state": "", "statename": location[0],
                "city": "", "cityname": location[1],
               "labelid": location[2], "room_type": "4"}
    text = URLHOST + "zhibo/createchatroom"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss), userMap=userMap)
    print(response)

# =====================================直播心跳任务
def 直播心跳任务(userMap, location):
    # {lat=30.554227, lng=104.071163, state=510000, statename=四川省, city=510100, cityname=成都市, uid=40076, labelid=1, room_type=1}
    paramss = {"uid": userMap["uid"], "key": userMap["uid"]}
    text = URLHOST + "zhibo/chargingroom"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss), userMap=userMap)
    try:
        json_to_python = json.loads(response)
        print("直播同步时间：: " + str(json_to_python["IsError"]) + "  ----  " + str(json_to_python["ErrorMessage"]))
        if 1 == json_to_python["IsError"]:
            开始直播(userMap, location)
    except Exception as e1:
        print("直播同步时间error ：" + str(e1))

# ======================================直播心跳任务循环
def 直播心跳任务循环(val, cell, location):
    print(val)
    userMap = login(cell, ALLCODE)  # 登录
    开始直播(userMap, location)
    for i in range(1, 1000):
        time.sleep(15)
        直播心跳任务(userMap, location)
# ======================================测试线程


def 登录开播心跳同步():
    # 创建两个线程
    try:
        userList = ["13541111101", "18782927715", "13541111102", "13541111103", "13541111104", "13541111105",
                    "13541111106", "13541111107", "13541111108", "13541111109", "13541111110", "13541111111",
                    "13541111112", "13541111113", "13541111114", "13541111115", "13541111116", "13541111117",
                    "13541111118", "13541111119", "13541111120", "13541111121", "13541111122", "13541111123",
                    "13541111124", "13541111125", "13541111126", "13541111127", "17708696472", "18811111188"]

        # 开播地址
        Location1 = ["广东省", "佛山市", "2"]
        Location2 = ["山东省", "济南市", "1"]
        Location3 = ["浙江省", "丽水市", "3"]
        Location4 = ["陕西省", "汉中市", "2"]
        Location5 = ["湖南省", "长沙市", "3"]
        Location6 = ["黑龙江省", "大庆市", "1"]
        Location7 = ["山东省", "济南市", "1"]
        Location8 = ["江苏省", " 无锡市", "1"]
        Location9 = ["河南省", "济源市", "2"]
        Location10 = ["上海市", "上海市", "1"]
        Location11 = ["河北省", "邯郸市", "3"]
        Location12 = ["浙江省", " 嘉兴市", "1"]
        Location13 = ["陕西省", "安康市", "2"]
        Location14 = ["福建省", "宁德市", "3"]
        Location15 = ["云南省", "曲靖市", "1"]
        Location16 = ["四川省", "达州市", "3"]
        Location17 = ["安徽省", "宿州市", "1"]
        Location18 = ["海南省", "东方市", "2"]
        Location19 = ["辽宁省", "辽阳市", "1"]
        Location20 = ["甘肃省", "武威市", "3"]

        # 需要先登录才能执行下面的操作
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-0", userList[0], Location17, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-1", userList[1], Location18, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-2", userList[2], Location19, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-3", userList[3], Location20, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-4", userList[4], Location5, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-5", userList[5], Location6, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-6", userList[6], Location17, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-7", userList[7], Location2, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-9", userList[9], Location4, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-10", userList[10], Location5, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-11", userList[11], Location6, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-12", userList[12], Location1, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-13", userList[13], Location2, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-14", userList[14], Location3, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-15", userList[15], Location4, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[16], Location5, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[17], Location6, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[18], Location7, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[19], Location8, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[21], Location10, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[22], Location11, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[23], Location12, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[24], Location13, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[25], Location14, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[26], Location15, ))


        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-8", userList[8], Location3, ))
        # _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[20], Location9, ))
        # 自己的主播号
        _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-16", userList[27], Location15, ))
        # 杨老师主播账号
        _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-17", userList[28], Location10, ))
        # 张洁主播号
        _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-17", userList[29], Location13, ))
    except:
        print("Error: 无法启动线程")
    while 1:
        pass


# 正式环境
# URLHOST = "http://api.yamizhibo.com/api/"
# ALLCODE = 831246  # 831246
# 测试环境
URLHOST = "http://api.cwoqu.com/api/"
ALLCODE = 202088
# =====================================================================================================================
# main 主函数
# ===================c==================================================================================================
if __name__ == '__main__':
    登录开播心跳同步()





